package cdc.retrofit.official.simplemockservice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cdc.retrofit.official.simpleservice.Contributor;
import cdc.retrofit.official.simpleservice.GitHub;
import retrofit2.Call;
import retrofit2.mock.BehaviorDelegate;

public class MockGitHub implements GitHub {
	
	private final BehaviorDelegate<GitHub> delegate;
	private final Map<String, Map<String, List<Contributor>>> ownerRepoContributors;

	@Override
	public Call<List<Contributor>> contributors(String owner, String repo) {
		List<Contributor> response = Collections.emptyList();
	      Map<String, List<Contributor>> repoContributors = ownerRepoContributors.get(owner);
	      if (repoContributors != null) {
	        List<Contributor> contributors = repoContributors.get(repo);
	        if (contributors != null) {
	          response = contributors;
	        }
	      }
	      return delegate.returningResponse(response).contributors(owner, repo);
	}

	

	MockGitHub(BehaviorDelegate<GitHub> delegate) {
		this.delegate = delegate;
		ownerRepoContributors = new LinkedHashMap<>();

		// Seed some mock data.
		addContributor("square", "retrofit", "John Doe", 12);
		addContributor("square", "retrofit", "Bob Smith", 2);
		addContributor("square", "retrofit", "Big Bird", 40);
		addContributor("square", "picasso", "Proposition Joe", 39);
		addContributor("square", "picasso", "Keiser Soze", 152);
	}

	void addContributor(String owner, String repo, String name, int contributions) {
		Map<String, List<Contributor>> repoContributors = ownerRepoContributors.get(owner);
		if (repoContributors == null) {
			repoContributors = new LinkedHashMap<>();
			ownerRepoContributors.put(owner, repoContributors);
		}
		List<Contributor> contributors = repoContributors.get(repo);
		if (contributors == null) {
			contributors = new ArrayList<>();
			repoContributors.put(repo, contributors);
		}
		contributors.add(new Contributor(name, contributions));
	}

}
